package com.cloud.music.config;


import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * RestTemplate配置类
 */
@Slf4j
@Configuration
public class RestTemplateConfig {

    /**
     * 常用远程调用RestTemplate
     * @return restTemplate
     */
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new AcceptResponseErrorHandler());
        return restTemplate ;
    }

    /**
     * 使RestTemplate能够对响应的错误消息不进行处理
     * 如：当响应码为400、500等错误时，能够不进行处理，最终用户可以获取到body数据
     */
    private static class AcceptResponseErrorHandler implements ResponseErrorHandler {

        @Override
        public boolean hasError(@NotNull ClientHttpResponse response) throws IOException {
            return false;
        }

        @Override
        public void handleError(@NotNull ClientHttpResponse response) throws IOException {

        }
    }

}